﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using VSWClient.Tables;
using Util;
using VSWClient.Tcp;
using VSWClient.Utility;
using VSWClient.Pages;
using VSWClient.Pages.Tables.L2PDB;
using System.Reflection;

namespace VSWClient
{
	/// <summary>
	/// Login.xaml interaction logic
	/// </summary>
	public partial class Login : Window
	{
		TcpClient client;
		public Login()
		{
			InitializeComponent();			
		}
		#region Login
		/// <summary>
		/// user login button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Btn_Login_Click(object sender, RoutedEventArgs e)
		{						
			try
			{
				ConfigHelper configHelper = new ConfigHelper();
				string serverIp = configHelper.GetConfig("SERVER_IP", System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\ServerIpConfig.xml");
				client = new TcpClient(serverIp, 2012);
				client.DealMessageHandler += Login_DealMessageHandler;
				if (client.Connect())
				{
					string name = string.IsNullOrEmpty(textBox_Name.Text) ? " " : textBox_Name.Text;
					string password = string.IsNullOrEmpty(textBox_Password.Password) ? "0" : textBox_Password.Password;
					string message = string.Format("{0};{1}", name, password);
					client.SendMessage(Identity.definedCommand, Identity.login, message);
					LogHelper.WriteLog("Btn_Login_Click");
				}
				else
				{
					MessageBox.Show(WarningMessages.ConnectFailed.message, WarningMessages.ConnectFailed.level);
					LogHelper.WriteLog("server connect fail");
				}					
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("Btn_Login_Click", ex);
				MessageBox.Show(ex.Message, "Alarm");
				client.Disconnect();
			}
		}
		#endregion

		#region Receive Message
		private void Login_DealMessageHandler(object sender, DealMessageHandlerArgs e)
        {
			try
			{
				string message = "";
				for (int i = 0; i < e.Message.Length; i++)
				{
					if (i==0)
					{
						message = e.Message[0];						
					}
					else
					{
						message= e.Message[i].Substring(2, e.Message[i].Length-2);
					}
					TcpMessageHelper msg = new TcpMessageHelper(message);
					//whether command is valid
					if (msg.Vaild)
					{
						if (msg.CommandId == Identity.login)
						{
							//if the login is successful，return the user table and shift table
							if (msg.Status)
							{
								try
								{
									DataTable[] tables = JsonHelper.DeserializeJsonToObject<DataTable[]>(msg.Parameter[0]);
									DataTable userTable = tables[0];
									DataTable shiftTable = tables[1];
									DataTable teamTable = tables[2];

									USER_TABLE.user_Level = userTable.Rows[0][USER_TABLE.fd_userLevel].ToString();
									USER_TABLE.create_Date = userTable.Rows[0][USER_TABLE.fd_createDate].ToString();
									USER_TABLE.user_Name = userTable.Rows[0][USER_TABLE.fd_userName].ToString();
									USER_TABLE.user_No = userTable.Rows[0][USER_TABLE.fd_userNo].ToString();
									USER_TABLE.user_Password = userTable.Rows[0][USER_TABLE.fd_userPassword].ToString();
									USER_TABLE.shift_Name = userTable.Rows[0][USER_TABLE.fd_shiftName].ToString();
									USER_TABLE.user_Department = userTable.Rows[0][USER_TABLE.fd_userDepartment].ToString();

									if (shiftTable.Rows.Count > 0)
									{
										SHIFT_TABLE.shifttable = shiftTable;
										SHIFT_TABLE.shifttable.TableName = SHIFT_TABLE.tableName;
									}
									if (teamTable.Rows.Count > 0)
									{
										TEAM_TABLE.teamtable = teamTable;
										TEAM_TABLE.teamtable.TableName = TEAM_TABLE.tableName;										
									}
									if (shiftTable.Rows.Count > 0 && teamTable.Rows.Count > 0)
									{
										TEAM_TABLE.CurrentShiftName = GetCurrentShift(shiftTable, teamTable, DateTime.Now);
									}
									
									//SHIFT_TABLE.Shift_Name = msg.Parameter[1];
									//window jump
									client.DealMessageHandler -= Login_DealMessageHandler;
									Dispatcher.Invoke(new Action(() =>
									{
										MainWindow mainWindow = new MainWindow(client, mainDict);
										mainWindow.Resources.MergedDictionaries.Clear();
										mainWindow.Resources.MergedDictionaries.Add(mainDict);
										mainWindow.Show();
										this.Close();
									}));
								}
								catch (Exception ex)
								{
									MessageBox.Show("Login success:" + ex.Message);
									client.Disconnect();
								}
							}
							else
							{
								MessageBox.Show(WarningMessages.LoginUnvaild.message, WarningMessages.LoginUnvaild.level);
								client.Disconnect();
							}
						}
					}
					//command is invalid
					else
					{
						MessageBox.Show(WarningMessages.LoginFailed.message, WarningMessages.LoginFailed.level);
						client.Disconnect();
					}
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
        }
		#endregion
		/// <summary>
		/// hide window
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Btn_Hide_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
		/// <summary>
		///close window
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void Btn_Close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
		/// <summary>
		/// move window
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void Btn_Drag_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ButtonState == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }
		/// <summary>
		/// change window size
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void Btn_Drag_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.WindowState == WindowState.Normal)
            {
                this.WindowState = WindowState.Maximized;
            }
            else
            {
                this.WindowState = WindowState.Normal;
            }
        }
		/// <summary>
		/// select language
		/// </summary>
        ResourceDictionary mainDict;
        private void Combox_selelanguage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ResourceDictionary dict = new ResourceDictionary();
            if (combox_selelanguage.SelectedIndex == 0)
            {
                dict.Source = new Uri("English.xaml", UriKind.Relative);
                mainDict = dict;
            }
            else
            {             
                dict.Source = new Uri("Russian.xaml", UriKind.Relative);
                mainDict = dict;
            }
            this.Resources.MergedDictionaries.Clear();
            this.Resources.MergedDictionaries.Add(dict);
        }
		/// <summary>
		/// get current shift
		/// </summary>
		/// <param name="shiftTable"></param>
		/// <param name="teamTable"></param>
		/// <param name="dateTime"></param>
		/// <returns></returns>
		private string GetCurrentShift(DataTable shiftTable,DataTable teamTable,DateTime dateTime)
		{
			try
			{
				string shiftName = "";
				//第一个班组的时间
				DateTime firstShiftdateTime = Convert.ToDateTime(teamTable.Rows[0][TEAM_TABLE.fd_shiftDate].ToString());
				//当前时间
				DateTime currentDate = Convert.ToDateTime(dateTime.ToString(Formats.GetShortFormat()));
				//当前时间与第一个班组的时间天数差
				int days = currentDate.Subtract(firstShiftdateTime).Days;
				if (days < 0)
				{
					MessageBox.Show("shiftDate in team table cannot be greater than the current time");
					return "";
				}
				//天数差跟TEAM_TABLE数据行数取余
				int remainder = days % teamTable.Rows.Count;

				//判断当前时间属于白班还是夜班
				string dayOrNightShift = "";
				for (int i = 0; i < shiftTable.Rows.Count; i++)
				{
					DateTime startTime = Convert.ToDateTime(shiftTable.Rows[i][SHIFT_TABLE.fd_startTime].ToString());
					DateTime endTime = Convert.ToDateTime(shiftTable.Rows[i][SHIFT_TABLE.fd_endTime].ToString());
					DateTime currentTime = Convert.ToDateTime(dateTime.ToString(Formats.GetTimeFormat()));
					if (startTime < endTime)
					{
						if (currentTime > startTime && currentTime < endTime)
						{
							dayOrNightShift = shiftTable.Rows[i][SHIFT_TABLE.fd_shiftName].ToString();
						}
					}
					else
					{
						if (currentTime > startTime || currentTime < endTime)
						{
							dayOrNightShift = shiftTable.Rows[i][SHIFT_TABLE.fd_shiftName].ToString();
						}
					}					
				}
				if (dayOrNightShift == "DAY")
				{
					shiftName = teamTable.Rows[remainder][TEAM_TABLE.fd_dayShift].ToString();
				}
				else if (dayOrNightShift == "NIGHT")
				{
					shiftName = teamTable.Rows[remainder][TEAM_TABLE.fd_nightShift].ToString();
				}
				LogHelper.WriteLog("GetCurrentShift");
				return shiftName;				
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("GetCurrentShift", ex);
				throw ex;
			}			
		}
    }
}
